# !/usr/bin/python
# -*- coding:utf8-*-

import redis
import time


class TestFunc:
    def __init__(self):
        self.conn = redis.Redis(host='localhost', port=6379)

    def add_uid(self, new_uid):
        '''
        新增uid
        :param new_uid:
        :return:
        '''
        if not self.conn.sismember('uids', new_uid):
            self.conn.sadd('uids', new_uid)
            for i in self.conn.smembers('tokenids'):
                print i
                self.conn.sadd('tid_avaliable_' + str(new_uid), i)

    def get_avaliable_tokens(self, uid, num):
        '''
        返回该uid对应可用的tokenid
        :param uid:
        :param num:
        :return:
        '''
        lis_rst = []
        uids = self.conn.smembers('uids')
        if uid in uids:
            for i in xrange(num):
                tokenid = self.conn.spop('tid_avaliable_' + uid)
                lis_rst.append(tokenid)
                self.conn.hincrby(tokenid, 'count', 1)
                cnt = self.conn.hget(tokenid, 'count')
                if cnt > 5:
                    for item in uids:
                        if item != uid:
                            self.conn.srem('tid_avaliable_' + item, tokenid)
                    self.conn.srem('tokenids', tokenid)
        return lis_rst


if __name__ == '__main__':
    test = TestFunc()
    ##添加新用户
    # test.add_uid('uid6')

    ##获取该uid可用的tokenids
    start = time.time()
    lis = test.get_avaliable_tokens('uid1', 5000)
    end = time.time()
    print '======================='
    print '取出-->' + str(len(lis)) + '条tokenid'
    print '耗时-->' + str(end - start) + '秒'
